package com.ruoyi.paip.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.ruoyi.paip.domain.paip.Response;

import java.net.URLEncoder;

public class JsonUtils {
    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        // 支持Java8时间类型
        mapper.registerModule(new JavaTimeModule());
        // 禁用日期转时间戳
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    }

    /**
     * 解析JSON到ApiResponse（简单类型）
     * @param json JSON字符串
     * @param dataClass data字段的类型（如String.class, Integer.class）
     * @return ApiResponse<T>
     */
    public static <T> Response<T> parse(String json, Class<T> dataClass) {
        try {
            return mapper.readValue(json, new TypeReference<Response<T>>() {
            });
        } catch (Exception e) {
            throw new RuntimeException("JSON解析失败", e);
        }
    }

    /**
     * 解析JSON到ApiResponse（复杂类型）
     * @param json JSON字符串
     * @param typeReference 带泛型的TypeReference（如new TypeReference<ApiResponse<PhoneCategoryData>>() {}）
     * @return ApiResponse<T>
     */
    public static <T> Response<T> parse(String json, TypeReference<Response<T>> typeReference) {
        try {
            return mapper.readValue(json, typeReference);
        } catch (Exception e) {
            throw new RuntimeException("JSON解析失败", e);
        }
    }

    /**
     * 对象转JSON字符串
     * @param obj 任意对象
     * @return JSON字符串
     */
    public static String toJson(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException("JSON生成失败", e);
        }
    }

    /**
     * 对象转JSON字符串
     * @param obj 任意对象
     * @return JSON字符串
     */
    public static String toJsonAndEncode(Object obj) {
        try {
            String jsonStr = mapper.writeValueAsString(obj);
          return  URLEncoder.encode(jsonStr, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("JSON生成失败", e);
        }
    }
}